<?php

namespace App\Task;

use App\Model\Act\UserRankAct;
use App\Model\UserProfile;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;

/**
 * 定时活动排行榜
 * @Crontab(name="ActRankTask", rule="15 03 * * *", callback="execute", memo="定时计算排行榜", singleton=true)
 */
class ActRankTask
{
    public $limit = 20;

    /**
     * @return void
     */
    public function execute()
    {
        log_info(__CLASS__ . "==Start==" . date('Y-m-d H:i:s'));
        //活动榜单
        $this->actRank();
        log_info(__CLASS__ . "==End==" . date('Y-m-d H:i:s'));
    }

    /**
     * 活动榜单
     */
    function actRank()
    {
        $start = null; //date('Y-m-d', strtotime('monday'));
        $rankInfo = [];
        $limitMax = ['chat' => 500, 'moment' => 300];
        //邀请充值 - 500
        $inviteInfo = UserRankAct::getInvitedRechargers($start);
        foreach ($inviteInfo as $profileId => $userIds) {
            $profile = UserProfile::getInfoByProfileId($profileId);
            if (!isset($rankInfo[$profile->user_id])) $rankInfo[$profile->user_id] = 0;
            $rankInfo[$profile->user_id] += 500 * count($userIds);
        }

        //私信
        $userChats = UserRankAct::getHostChatRecords($start);
        foreach ($userChats as $userChat) {
            $hostId = $userChat->user_id;
            if (!isset($rankInfo[$hostId])) $rankInfo[$hostId] = 0;
            //发送一条私信 - 1
            $rankInfo[$hostId] += $userChat->msg_num * 1;
            //得到回复 - 50
            if ($userChat->chat_msg_num > 0) $rankInfo[$hostId] += 50;
        }

        //接听语音电话
        $voiceCalls = UserRankAct::getHostVoicecalls($start);
        foreach ($voiceCalls as $voiceCall) {
            $hostId = $voiceCall['chat_user_id'];
            if (!isset($rankInfo[$hostId])) $rankInfo[$hostId] = 0;
            //一分钟语聊内 - 50
            $voiceCall['call_time'] <= 60 && $rankInfo[$hostId] += 50;
            //两分钟以上 - 100
            $voiceCall['call_time'] > 60 && $rankInfo[$hostId] += 100;
        }

        //发布动态 - 50
        $moments = UserRankAct::getMoments($start);
        foreach ($moments as $moment) {
            $userId = $moment['user_id'];
            if (!isset($rankInfo[$userId])) $rankInfo[$userId] = 0;
            $rankInfo[$userId] += 50;
        }

        //数量小于10
        if (count($rankInfo) < 10) return false;

        //清除记录
        $sql = "TRUNCATE t_user_rank_activity";
        Db::statement($sql);

        //入库
        arsort($rankInfo);
        $rank = 1;
        foreach ($rankInfo as $userId => $rankValue) {
            UserRankAct::addRecord($userId, $rankValue, $rank++, UserRankAct::ACT_HOST_RANK);
        }
    }
}
